using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager
{
    
    
    private static UIManager _instance;

    public static UIManager Instance
    {
        get
        {
            if (_instance==null)
            {
                _instance = new UIManager();
            }

            return _instance;
        }
    }

    private Dictionary<string, string> pathDict;

    private Transform _uiRoot;

    public Transform UIRoot
    {
        get
        {
            if (_uiRoot==null)
            {
                _uiRoot = GameObject.Find("Canvas").transform;
            }
            return _uiRoot;
        }
    }

    //预制件缓存字典
    private Dictionary<string, GameObject> prefabDict;

    //已经打开界面的缓存字典
    public Dictionary<string, BasePanel> panelDict;
    private UIManager()
    {
        InitDicts();
    }
    

    private void InitDicts()
    {
        pathDict = new Dictionary<string, string>()
        {
            {UIConst.ShowBattleInfoPanel,"ShowBattleInfoPanel"},
            {UIConst.BattlePanel,"BattlePanel"},
            {UIConst.InfoPanel,"InfoPanel"},
        };
        prefabDict = new Dictionary<string, GameObject>();
        panelDict = new Dictionary<string, BasePanel>();
    }


    public BasePanel OpenPanel(string name,params object[] args)
    {
        BasePanel panel = null;
        if (panelDict.TryGetValue(name,out panel))
        {
            Debug.LogError("界面已打开："+name);
            return null;
        }

        string path = "";
        if (!pathDict.TryGetValue(name,out path))
        {
            Debug.LogError("界面名称错误，或未配置路径："+name);
            return null;
        }

        GameObject panelPrefab = null;
        if (!prefabDict.TryGetValue(name,out panelPrefab))
        {
            string realpath = "Prefabs/Panel/" + path;
            panelPrefab = Resources.Load<GameObject>(realpath) as GameObject;
            prefabDict.Add(name,panelPrefab);
        }
        
        //打开界面
        GameObject panelObject = GameObject.Instantiate(panelPrefab, UIRoot, false);
        panel = panelObject.GetComponent<BasePanel>();
        panelDict.Add(name,panel);
        panel.OpenPanel(name,args);
        return panel;
    }

    public bool ClosePanel(string name)
    {
        BasePanel panel = null;
        if (!panelDict.TryGetValue(name,out panel))
        {
            Debug.LogError("界面未打开："+name);
            return false;
        }
        panel.ClosePanel();
        return true;
    }
}

public class UIConst
{
    public const string ShowBattleInfoPanel = "ShowBattleInfoPanel";
    public const string BattlePanel = "BattlePanel";
    public const string InfoPanel = "InfoPanel";
}